<template>
  <div :class="{'mobile-create': showMobilePage}" class="create-invoice">
    <div class="invoice-form">
      <Title :title="isEdit? '编辑发票' : '新增发票'" font-size="16px" style="margin-bottom: 16px" />
      <div class="base-info-box">
        <BaseInfoEdit
          ref="baseInfoEdit"
          :invoice-status="invoiceStatus"
          :base-info="baseInfo"
          :is-init="isInit"
          :related-order="baseInfo.relatedOrder"
          :update-customers="updateCustomers"
          :order-ids="orderIds"
          :default-proposer-list="defaultProposers"
          :default-customer-list="defaultCustomers"
          :show-mobile-page="showMobilePage"
          @update:baseInfo="updateBaseInfo"
        />
      </div>
    </div>
    <div class="invoice-form">
      <Title font-size="16px" title="发票信息" style="margin-bottom: 16px" />
      <div class="base-info-box">
        <InvoiceInfoEdit ref="invoiceInfoEdit" :invoice-status="invoiceStatus" :invoice-info="invoiceInfo" :detail-info="invoiceDetail" @update:formValid="updateInvoiceInfoValid" @update:invoiceInfo="updateInvoiceInfo" />
      </div>
    </div>
    <div class="invoice-form">
      <Title font-size="16px" title="寄送信息" style="margin-bottom: 16px" />
      <div class="base-info-box">
        <SendInfoEdit :send-info="sendInfo" :invoice-status="invoiceStatus" @update:sendInfo="updateSendInfo" />
      </div>
    </div>
    <fixed-pagination>
      <div class="center">
        <el-button :loading="btnLoading" type="primary" size="small" class="submit-btn" @click="toSubmit">保存</el-button>
        <el-button type="info" size="small" class="back-btn cancel-btn-style" @click="toBack">取消</el-button>
        <el-popconfirm v-if="isEdit && invoiceStatus === 2 && hasRouteAuth('crm:receipt:arch')" title="封存后只能关联订单，其他信息不可编辑！" @onConfirm="toArch">
          <el-button slot="reference" :loading="btnLoading" style="margin-left:10px" type="primary" plain size="small">封存</el-button>
        </el-popconfirm>
      </div>
    </fixed-pagination>
  </div>
</template>
<script>
import Title from '@/components/Title';
import BaseInfoEdit from './module/base-info-edit';
import InvoiceInfoEdit from './module/invoice-info-edit';
import SendInfoEdit from './module/send-info-edit';
import { hasRouteAuth } from '@/utils/permission';
import { createInvoice, editInvoice, invoiceDetail, invoiceRelatedOrderIds, getClientSingleInfo, archInvoice } from '@/api/invoice';
import { mapState } from 'vuex';
import mobileCreate from '@/mixins/mobileCreate';
import ElMessage from '@/utils/message';
export default {
  components: { Title, BaseInfoEdit, InvoiceInfoEdit, SendInfoEdit },
  mixins: [mobileCreate],
  data() {
    return {
      invoiceId: '',
      isInit: true,
      antiShakeTime: 0, // 防抖时间
      isEdit: false,
      invoiceInfoFormValid: false,
      invoiceDetail: null,
      btnLoading: false,
      defaultProposers: [],
      defaultCustomers: [],
      updateCustomers: null,
      updateClientInfo: null,
      isUpdate: false,
      invoiceStatus: 0,
      sendInfo: {
        contacts: '',
        deliveryAddress: '',
        deliveryPhone: '',
        prefixAddress: [],
        detailedAddress: '',
        postalCode: ''
      },
      baseInfo: {
        proposerId: '',
        clientName: '',
        deptId: '',
        title: '',
        invoiceTypeId: '',
        customerId: '',
        taxpayerNum: '',
        date: '',
        relatedOrder: [],
        openBank: '',
        accountNum: '',
        phone: '',
        amount: '',
        remark: '',
        invoiceAddress: ''
      },
      invoiceInfo: {
        no: '',
        number: '',
        attachment: '',
        attachmentUrl: ''
      }
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    orderIds() {
      const ids = this.baseInfo.relatedOrder.map(item => item.id);
      return JSON.parse(JSON.stringify(ids));
    }
  },
  created() {
    this.invoiceId = Number(this.$route.params.id) || '';
    if (this.invoiceId) {
      this.isEdit = true;
      this.getInvoiceDetail(this.invoiceId);
    }
    if (this.$route.query.ids) {
      this.invoiceRelatedOrderIds(JSON.parse(this.$route.query.ids));
    }
  },
  methods: {
    hasRouteAuth,
    // 获取关联订单
    invoiceRelatedOrderIds(ids) {
      const params = {
        ids: ids
      };
      invoiceRelatedOrderIds(params).then(res => {
        if (res.code === 200) {
          this.isInit = false;
          this.baseInfo.relatedOrder = res.data;
        }
      });
    },
    async asyncGetInvoiceDetail(id) {
      try {
        const res = await invoiceDetail(id);
        if (res.code === 200) {
          this.invoiceDetail = res.data;
          this.initBaseInfo(res.data);
          this.initSendInfo(res.data);
          this.initInvoiceInfo(res.data);
          this.invoiceId = id;
        }
      } catch (e) {
        console.log(e);
      }
    },
    getInvoiceDetail(id) {
      invoiceDetail(id).then(res => {
        if (res.code === 200) {
          this.invoiceDetail = res.data;
          this.invoiceStatus = res.data.status || 0;
          this.isInit = false;
          this.initBaseInfo(res.data);
          this.initSendInfo(res.data);
          this.initInvoiceInfo(res.data);
          this.getClientSingleInfo(this.invoiceDetail.client.id);
          this.invoiceId = id;
        }
      });
    },
    // 判断数据是否更新
    getClientSingleInfo(id) {
      if (!id) return;
      getClientSingleInfo(id).then(res => {
        if (res.code === 200) {
          this.updateClientInfo = res.data;
          const updateClientInfo = this.updateClientInfo;
          const invoiceDetail = this.invoiceDetail.client;
          const clientNameBoolean = updateClientInfo.clientName && updateClientInfo.clientName !== invoiceDetail.clientName;
          const openBankBoolean = updateClientInfo.openBank && updateClientInfo.openBank !== invoiceDetail.openBank;
          const accountNumNameBoolean = updateClientInfo.accountNum && updateClientInfo.accountNum !== invoiceDetail.accountNum;
          const taxpayerNumBoolean = updateClientInfo.taxpayerNum && updateClientInfo.taxpayerNum !== invoiceDetail.taxpayerNum;
          const phoneBoolean = updateClientInfo.phone && updateClientInfo.phone !== invoiceDetail.phone;
          const invoiceAddressBoolean = updateClientInfo.invoiceAddress && updateClientInfo.invoiceAddress !== invoiceDetail.invoiceAddress;
          if (clientNameBoolean || openBankBoolean || accountNumNameBoolean || taxpayerNumBoolean || phoneBoolean || invoiceAddressBoolean) {
            this.$confirm('纳税名称信息有更新是否需要更新', '', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              center: true,
              type: 'warning',
              customClass: 'del-message del-message-cancel',
              iconClass: 'del-icon'
            }).then(() => {
              this.baseInfo['clientName'] = updateClientInfo.clientName || '';
              this.baseInfo['openBank'] = updateClientInfo.openBank || '';
              this.baseInfo['accountNum'] = updateClientInfo.accountNum || '';
              this.baseInfo['taxpayerNum'] = updateClientInfo.taxpayerNum || '';
              this.baseInfo['phone'] = updateClientInfo.phone || '';
              this.baseInfo['invoiceAddress'] = updateClientInfo.invoiceAddress || '';
              this.isUpdate = true;
              this.updateCustomers = updateClientInfo;
            });
          }
        }
      });
    },
    initSendInfo(data) {
      const sendInfo = {
        contacts: data.contacts,
        deliveryAddress: data.deliveryAddress,
        deliveryPhone: data.deliveryPhone,
        prefixAddress: JSON.parse(data.prefixAddress),
        detailedAddress: data.detailedAddress,
        postalCode: data.postalCode
      };
      this.sendInfo = sendInfo;
    },
    initInvoiceInfo(data) {
      const invoiceInfo = {
        no: data.no,
        number: data.number,
        attachment: data.attachment,
        attachmentUrl: data.attachmentUrl
      };
      this.invoiceInfo = invoiceInfo;
    },
    initBaseInfo(data) {
      const baseInfo = {
        proposerId: data.proposer.id || '',
        deptId: data.department.id || '',
        title: data.title || '',
        invoiceTypeId: data.invoiceTypeId || '',
        customerId: data.client.id || '',
        clientName: data.client.clientName || '',
        taxpayerNum: data.client.taxpayerNum || '',
        date: this.switchTimestamp(data.invoiceDate),
        relatedOrder: data.relatedOrderIds || [],
        openBank: data.client.openBank || '',
        accountNum: data.client.accountNum || '',
        phone: data.client.phone || '',
        amount: data.amount,
        remark: data.remark || '',
        invoiceAddress: data.client.invoiceAddress || ''
      };
      if (data.proposer.id) {
        this.defaultProposers.push(data.proposer);
      }
      if (data.client.id) {
        this.defaultCustomers.push(data.client);
      }
      this.baseInfo = baseInfo;
    },
    switchTimestamp(dateStr) {
      if (!dateStr) return '';
      dateStr = dateStr.substring(0, 19);
      dateStr = dateStr.replace(/-/g, '/');
      const timestamp = new Date(dateStr).getTime();
      return timestamp;
    },
    createInvoice(params) {
      createInvoice(params).then(res => {
        this.btnLoading = false;
        if (res.code === 200) {
          ElMessage.success('创建成功');
          this.$router.push({
            name: 'invoice'
          });
        } else {
          ElMessage.error(res.message);
        }
      }).catch(err => {
        this.btnLoading = false;
        console.log(err);
      });
    },
    editInvoice(id, params) {
      editInvoice(id, params).then(res => {
        this.btnLoading = false;
        if (res.code === 200) {
          ElMessage.success('编辑成功');
          this.$router.push({
            name: 'invoice'
          });
        } else {
          ElMessage.error(res.message);
        }
      }).catch(err => {
        this.btnLoading = false;
        console.log(err);
      });
    },
    toSubmit() {
      var timestamp = Date.parse(new Date());
      if (timestamp - this.antiShakeTime < 500) {
        return;
      }
      this.antiShakeTime = timestamp;
      const validatePromise = [];
      if (this.$refs.baseInfoEdit) validatePromise.push(this.$refs.baseInfoEdit.validateForm());

      const params = { ...this.baseInfo, ...this.invoiceInfo, ...this.sendInfo };
      if (params.prefixAddress) {
        params.prefixAddress = JSON.stringify(params.prefixAddress);
      }
      if (params.relatedOrder) {
        params.relatedOrder = JSON.stringify(params.relatedOrder);
      }
      if (params.amount.toString()) {
        params['amountFen'] = Math.round(Number(params.amount) * 100);
      }
      Promise.all(validatePromise).then(res => {
        this.btnLoading = true;
        if (this.isEdit) {
          this.editInvoice(this.invoiceId, JSON.parse(JSON.stringify(params)));
        } else {
          this.createInvoice(JSON.parse(JSON.stringify(params)));
        }
      }).catch((err) => {
        this.btnLoading = false;
        console.error(err);
        ElMessage.warning('请检查信息是否填写完整');
      });
    },
    toArch() {
      var timestamp = Date.parse(new Date());
      if (timestamp - this.antiShakeTime < 500) {
        return;
      }
      this.antiShakeTime = timestamp;
      archInvoice(this.invoiceId).then(res => {
        if (res.code === 200) {
          this.getInvoiceDetail(this.invoiceId);
          this.$message.success('封存成功');
        }
      });
    },
    toBack() {
      this.$router.push({
        name: 'invoice'
      });
    },
    updateInvoiceInfoValid(value) {
      this.invoiceInfoFormValid = value;
    },
    updateBaseInfo(data) {
      this.baseInfo = data;
    },
    updateInvoiceInfo(data) {
      this.invoiceInfo = data;
    },
    updateSendInfo(data) {
      this.sendInfo = data;
    }
  }
};
</script>
<style lang="scss" scoped>
.create-invoice {
  margin: 16px;
  background-color: #fff;
  padding: 24px 24px 50px 24px;
  min-height: calc(100vh - 70px);
  .invoice-form {
    margin-bottom: 10px;
    &::v-deep {
      .el-input {
        font-size: 14px !important;
      }
    }
  }
  .arch-btn {
    // background: #fff;
    height: 40px;
    margin-left: 10px;
    &.el-button--primary.is-plain {
      background: #fff;
    }
    &.el-button--primary {
      color: #406EFF;
    }
  }
}
</style>
<style lang="scss">
.create-invoice {
  .el-input__inner {
    height: 32px;
    line-height: 32px;
    width: 240px;
  }
  .el-input__icon {
    line-height: 32px;
  }
  .el-form-item{
    margin-bottom: 24px;
  }
  .el-select {
    .el-input {
      .el-select__caret {
        color: #333333;
      }
    }
  }
}
</style>

